package com.ayoka.ui.training;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;

import com.ayoka.R;
import com.ayoka.base.BaseActivity;
import com.ayoka.databinding.ActivityTrainingDetailBinding;
import com.ayoka.mvp.TrainingDetailMVP.TrainingDetailModel.ResponseTrainingDetailBean;
import com.ayoka.mvp.TrainingDetailMVP.ITrainingDetailView;
import com.ayoka.mvp.TrainingDetailMVP.TrainingDetailModel.TrainingDetailBean;
import com.ayoka.mvp.TrainingDetailMVP.TrainingDetailPresenter;
import com.ayoka.utils.AudioManagerEvent;
import com.ayoka.utils.CourseEvent;
import com.ayoka.utils.MediaManager;
import com.jcp.baselibrary.model.ToolBarOptions;
import com.jcp.baselibrary.utils.DateUtil;
import com.jcp.baselibrary.utils.StatusBarUtils;
import com.jcp.baselibrary.utils.TDevice;
import com.jcp.baselibrary.utils.UIUtils;

import java.util.Observable;

/**
 * @author jcp
 * @ClassName: TopicListActivity
 * @Description:
 * @date 2018-12-28 下午4:21:18
 */
public class TrainingDetailActivity extends BaseActivity<ActivityTrainingDetailBinding, TrainingDetailPresenter> implements ITrainingDetailView {

    public static void start(Activity activity, long meditationId) {
        Intent intent = new Intent(activity, TrainingDetailActivity.class);
        intent.putExtra("MeditationId", meditationId);
        activity.startActivityForResult(intent, REQUEST_CODE_FOR_RESULT);
    }

    private long meditationId;
    private TrainingDetailBean trainingDetailBean;
    private int duration;

    private long recordId;

    private boolean isCompleted;

    @Override
    protected void configIntentValue() {
        meditationId = getIntent().getLongExtra("MeditationId", 0);
    }

    @Override
    protected void onBeforeSetContentLayout() {
        StatusBarUtils.setStatusBar(this, false, false);
        StatusBarUtils.setStatusTextColor(this, false);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_training_detail;
    }

    @Override
    protected void initViews() {
        mDataBinding.customToolbar.toolbar.setPadding(0, 0, 0, 0);
        mDataBinding.tvSelectVr.setOnClickListener(this);
        mDataBinding.btnPlay.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ToolBarOptions options = new ToolBarOptions(R.string.training);
        options.backgroundResource = 0;
        options.navigateId = R.mipmap.icon_back_white;
        options.titleColor = Color.WHITE;
        setCustomToolBar(mDataBinding.customToolbar.toolbar, options);

        // 设置监听
        MediaManager.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().requestAudioFocus();
        mPresenter.getTrainingDetailData(meditationId);

        mPresenter.showStartMeditationDialog(getSupportFragmentManager());
    }

    @Override
    protected TrainingDetailPresenter getPresenter() {
        return new TrainingDetailPresenter();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.btnPlay) {
            if (TDevice.isInstallByPackageName(this, "com.ayuk.Acrophobia")) {
                TDevice.openAppActivity(this, "com.ayuk.Acrophobia", "com.unity3d.player.UnityPlayerActivity");
            } else {
                UIUtils.openBrowser(this, "https://www.pgyer.com/NnUz");
            }
        }
        if (view == mDataBinding.btnPlay) {
            if (trainingDetailBean == null) return;
            onPlayClick(view);
        }
    }

    private void onPlayClick(View view) {
        if (MediaManager.getInstance().getPlayStatus() == MediaManager.PLAY) {
            MediaManager.getInstance().pause();
        } else if (MediaManager.getInstance().getPlayStatus() == MediaManager.PAUSE) {
            MediaManager.getInstance().resume();
        } else if (MediaManager.getInstance().getPlayStatus() == MediaManager.STOP) {
            MediaManager.getInstance().start();
        } else if (MediaManager.getInstance().getPlayStatus() == MediaManager.RELEASE) {
            MediaManager.getInstance().setMediaDataSource(this, trainingDetailBean.SoundUrl);
            mDataBinding.btnPlay.setOnClickListener(null);
            mDataBinding.progressLoading.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void configTrainingDetailData(ResponseTrainingDetailBean responseTrainingDetailBean) {
        if (responseTrainingDetailBean == null || responseTrainingDetailBean.meditation == null)
            return;
        this.trainingDetailBean = responseTrainingDetailBean.meditation;
        this.recordId = responseTrainingDetailBean.record_id;
        mDataBinding.tvTitle.setText(trainingDetailBean.Title);
        mDataBinding.tvName.setText(trainingDetailBean.SubTitle);
        invalidateOptionsMenu();
    }

    @Override
    public void onQuitClick() {
        finish();
    }

    @Override
    public void onOperationSuccess() {
        CourseEvent.getInstance().notifyOCourseChanged();
    }

    @Override
    public void onBackPressed() {
        if (MediaManager.getInstance().getPlayStatus() == MediaManager.PLAY) {
            mPresenter.showConfirmQuitMeditationDialog(getSupportFragmentManager(), getString(R.string.meditation_not_yet_completed));
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void update(Observable observer, Object object) {
        super.update(observer, object);
        if (observer instanceof AudioManagerEvent) {
            int focusChange = (int) object;
            if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                //获得焦点之后的操作
                MediaManager.getInstance().start();
            } else {
                //失去焦点之后的操作
                MediaManager.getInstance().pause();
            }
        }
        if (observer instanceof MediaManager) {
            MediaManager.OperatorResultBean operatorResultBean = (MediaManager.OperatorResultBean) object;
            // 获取时长
            if (operatorResultBean.operation == MediaManager.OperatorResultBean.GET_MEDIA_DURATION) {
                this.duration = (int) operatorResultBean.operatorValue;
                mDataBinding.circleProgress.setMaxProgress(duration);
                mDataBinding.progressLoading.setVisibility(View.GONE);
                mDataBinding.btnPlay.setOnClickListener(this);
                MediaManager.getInstance().start();
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_PROGRESS_UPDATE) {// 更新播放进度
                int progress = (int) operatorResultBean.operatorValue;
                long leftMills = duration - progress;
                mDataBinding.tvTime.setText(DateUtil.formatTime(leftMills / 1000));
                mDataBinding.circleProgress.setProgress(progress);
                if (!isCompleted && leftMills < 10 * 1000) {
                    mPresenter.AddMeditationRecord(recordId);
                    isCompleted = true;
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_UPDATE) {// 更新缓冲进度

            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_START) {// 开始播放
                mDataBinding.btnPlay.setText("暂停");
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_STOP) {// 开始播放
                mDataBinding.btnPlay.setText("播放");
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_COMPLETION) {// 播放完成
                mDataBinding.circleProgress.setProgress(0);
                mDataBinding.tvTime.setText("00:00");
                TrainingCompletedActivity.start(TrainingDetailActivity.this, trainingDetailBean.PackageID);
                finish();
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_START) {// 开始缓冲
                mDataBinding.progressLoading.setVisibility(View.VISIBLE);
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_END) {// 结束缓冲
                mDataBinding.progressLoading.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onDestroy() {
        MediaManager.getInstance().release();
        MediaManager.getInstance().deleteObserver(this);
        AudioManagerEvent.getInstance().deleteObserver(this);
        AudioManagerEvent.getInstance().abandonAudioFocus();
        super.onDestroy();
    }
}
